//添加商品

const productId = "pro" + require(path.resolve(basename, "utils/userId.js"));
module.exports = (req, res) => {
    let file = req.file;
    let nameArr = file.originalname.split(".");
    // console.log("req.file", file);
    let basePath = basename + "/public/images/";
    let oldPath = basePath + file.filename;
    let newPath = basePath + nameArr[0] + Date.now() + "." + nameArr[1];
    let newName = nameArr[0] + Date.now() + "." + nameArr[1];
    if(fs.existsSync(basePath)){
        fs.rename(oldPath,newPath,err=> {
            if(err){
                throw err;
            }
            // res.send("test controller success");
        })
    }
    let imgUrl = `http://localhost:3000/static/images/${newName}`;
    // console.log(imgUrl);
    let time = new Date;
    function double(num){
        if(num<10){
            return "0"+num
        }else{
            return num
        }
    }

    let now = time.getFullYear() + "-" + double(time.getMonth()+1) + "-" + double(time.getDate());
    
    // 获取cookie传过来的token进行验证
    let arr = req.headers.cookie.split(';');
    let itemObj = {};
    arr.forEach(item => {
        let itemArr = item.trim().split("=");
        itemObj[itemArr[0]] = itemArr[1];
    });
    let token = itemObj.fskl + "." + itemObj.sswr + "." + itemObj.ttnk;
    // console.log(token);
    let userId = "";
    // 获取用户id
    jwt.verify(token, 't-o_ken', function (err, decoded) {
        userId = decoded.data;
    });

    // console.log(req.body);
    let newProduct = new model.Product({
        name: req.body.name,
        productStatus: req.body.productStatus,
        type: req.body.type,
        desc: req.body.productdesc,
        images: imgUrl,
        productId: productId,
        price: req.body.productPrice,
        num: req.body.num,
        userId: userId,
        createAt: now
    })
    newProduct.save().then(result => {
        // console.log(result);
        res.send({
            code:"200",
            status:"405",
            msg:"商品添加成功"
        })
    })
    // res.send("success")
}